var glob = require('glob')
var path = require('path')
var fs   = require('fs')

exports.listFiles = function (filePath) {
  return function (symlink) {
    return function(hidden) {
      return function(ignore) {
        return function() {
          filePath = filePath.split(path.sep).join('/');
          var fullDir = filePath + (filePath.endsWith('/') ? '' : '/');
          var dirName = fullDir.split('/');
          dirName = dirName[dirName.length - 2] + '/';
      
          const mg = new glob.sync.GlobSync('**/*', {
            cwd: filePath,
            follow: symlink,
            dot: hidden,
            ignore: ignore
          });
          var mapFile = mg.found.map(function(name){
            const fqn = fullDir + name;
            //symlinks
            if(mg.symlinks[fqn] === true) {
              return {
                path:dirName + name,
                symlink:true,
                dir:false,
                content:fs.readlinkSync(fqn)
              };
            }
            //files
            if(mg.cache[fqn] === 'FILE') {
              return {
                path:dirName + name,
                symlink:false,
                dir:false,
                content:fs.createReadStream(fqn)
              };
            }
            //directories
            if(mg.cache[fqn] === 'DIR' || mg.cache[fqn] instanceof Array) {
              return {
                path:dirName + name,
                symlink: false,
                dir: true,
                content:null
              };
            }
          }).filter(Boolean);
          return mapFile;
        }
      }
    }
  }
}